package jsf;

import bean.BuyManager;
import bean.UserManager;
import java.util.List;
import jpa.entities.Cor;
import java.io.Serializable;
import jpa.entities.Produto;
import jsf.util.JsfUtil;
import jsf.util.PaginationHelper;
import jpa.session.ProdutoFacade;


import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.event.ActionEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpServletRequest;
import jpa.entities.Tamanho;
import org.richfaces.component.UICommandButton;

@ManagedBean(name = "produtoController")
@SessionScoped
public class ProdutoController implements Serializable {

    private Produto current = null;
    private UserManager login = null;
    private String clean = null;
    private Produto produto = null;
    private List<Produto> produtos = null;
    private DataModel items = null;
    private BuyManager compra = null;
    @EJB
    private jpa.session.ProdutoFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private int idExterna = 0;

    public ProdutoController() {
        this.recreateModel();
        this.produto = new Produto();
        this.compra = new BuyManager();
        ejbFacade = new jpa.session.ProdutoFacade();
    }

     public static Object queryString(String key)
    {
        HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();

        return request.getParameter(key);

    }

    public Produto getProduto() {
        //FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("produtoController");
        return produto;

    }
    public void setSelected(Integer idProduto){
        if (current == null) {
            current = new Produto();
            selectedItemIndex = -1;
        }
        current.setIdProduto(idProduto);

    }
    public Produto getSelected() {
        if (current == null) {
            current = new Produto();
            selectedItemIndex = -1;
        }
        this.produtos = getFacade().findFilters(current);
        return current;
    }

    public String getClean() {

        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("produtoController");
        return "";
    }

    public String getPrepareCreate() {
        this.prepareCreate();
        return "";
    }
    public String getPrepareView(){
        this.prepareViewEspecifica();
        return "";
    }

    private ProdutoFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
                public DataModel createPageConsultaDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {

        recreateModel();
        return "List";
    }

    public String prepareView() {

        current = (Produto) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();

        return "View";
    }
    public String prepareViewEspecifica() {

        current = getFacade().find(current.getIdProduto());
        return "View";
    }

    public String prepareCreate() {

        selectedItemIndex = -1;
        this.prepareList();
        return "Create";
    }

    public String create() {
        try {

            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("ProdutoCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit(ActionEvent event) {
        this.produto = new Produto();
        current = (Produto) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String prepareEdit() {
        this.produto = new Produto();
        current = (Produto) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }
    public String update() {
        try {
            
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("ProdutoUpdated"));
            recreateModel();

            return "Create";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String updateEstoque() {
        try {
            current = (Produto) getItems().getRowData();
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("ProdutoUpdated"));
            current = null;
            return "Create";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Produto) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "Create";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("ProdutoDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    public DataModel getProdutos() {
        //FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("produtoController");

        if (current == null) {
            this.produtos = getFacade().findAll();
             selectedItemIndex = -1;
        }
        DataModel model = new ListDataModel(produtos);
        return model;

    }

    private void recreateModel() {
        this.produto = new Produto();
        this.selectedItemIndex = -1;
        this.current = null;
        this.items = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = Produto.class)
    public static class ProdutoControllerConverter implements Converter {

        @Override
        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            ProdutoController controller = (ProdutoController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "produtoController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuilder sb = new StringBuilder();
            sb.append(value);
            return sb.toString();
        }

        @Override
        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Produto) {
                Produto o = (Produto) object;
                return getStringKey(o.getIdProduto());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + ProdutoController.class.getName());
            }
        }
    }

    public void corSelected(ActionEvent event) {

        UICommandButton button = (UICommandButton) event.getSource();
        if (button.getValue().toString().toUpperCase().equals("TODOS")) {
            current.setCor(null);
        } else {
            current.setCor(((Cor) button.getValue()));
        }

        this.getSelected();

    }

    public void tamanhoSelected(ActionEvent event) {

        UICommandButton button = (UICommandButton) event.getSource();
        if (button.getValue().toString().toUpperCase().equals("TODOS")) {
            current.setTamanho(null);
        } else {
            current.setTamanho(((Tamanho) button.getValue()));
        }

        this.getSelected();

    }
}
